package cn.tedu.jxdm.service.impl;

import cn.tedu.jxdm.ex.ServiceException;
import cn.tedu.jxdm.mapper.ProductMapper;
import cn.tedu.jxdm.pojo.dto.ProductDTO;
import cn.tedu.jxdm.pojo.entity.Product;
import cn.tedu.jxdm.pojo.vo.ProductDetailVO;
import cn.tedu.jxdm.pojo.vo.ProductIndexVO;
import cn.tedu.jxdm.service.IProductService;
import cn.tedu.jxdm.web.ServiceCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
@Service
public class ProductServiceImpl implements IProductService {
    @Autowired
    ProductMapper mapper;
    @Override
    public void insert(ProductDTO productDTO) {
        Product p=new Product();
        BeanUtils.copyProperties(productDTO,p);
        p.setCreated(new Date());
        int insert = mapper.insert(p);
        if (insert != 1) {
            String message = "添加失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public ProductDetailVO selectDetailById(int id, HttpSession session) {
        String info=(String) session.getAttribute("view"+id);
        if (info==null){
            //让商品的浏览量+1
            mapper.updateViewCountById(id);
            session.setAttribute("view"+id,"visited");
        }
        ProductDetailVO productDetailVO = mapper.selectDetailById(id);
        if (productDetailVO==null){
            String message = "获取详情失败，尝试访问的数据不存在！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return productDetailVO;
    }

    @Override
    public List<ProductIndexVO> selectIndex() {
        List<ProductIndexVO> productIndexVOS = mapper.selectIndex();
        System.out.println(productIndexVOS);
        if (productIndexVOS==null){
            String message = "获取详情失败，尝试访问的数据不存在！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return productIndexVOS;
    }

    @Override
    public List<ProductIndexVO> selectByWd(String wd) {
        List<ProductIndexVO> productIndexVOS = mapper.selectByWd(wd);
        if (productIndexVOS==null){
            String message="查询失败，尝试访问的数据不存在！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return productIndexVOS;
    }

    @Override
    public List<ProductIndexVO> selectByCid(int id) {
        List<ProductIndexVO> productIndexVOS = mapper.selectByCid(id);
        if (productIndexVOS==null){
            String message="查询失败，尝试访问的数据不存在！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return productIndexVOS;
    }
}


